package com.fzkjjt.easyexceldemo.controller;

import com.fzkjjt.easyexceldemo.api.vo.DemoData;
import com.fzkjjt.easyexceldemo.api.vo.DemoData2;
import com.fzkjjt.easyexceldemo.excel.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: easyexcel-demo
 * @description:
 * @author: FangZhen
 * @create: 2020-04-17 14:12
 **/
@RestController
@RequestMapping("/excel_controller")
@Api(tags = "excel测试")
public class ExcelController {

    /**
     * 读取 Excel（允许多个 sheet）
     */
    @PostMapping("readExcelWithSheets")
    @ApiOperation("读取 Excel（允许多个 sheet）")
    public Object readExcelWithSheets(MultipartFile excel) {
        return ExcelUtil.readExcel(excel, new DemoData2());
    }

    /**
     * 读取 Excel（指定某个 sheet）
     */
    @PostMapping("readExcel")
    @ApiOperation("读取 Excel（指定某个 sheet）")
    public Object readExcel(MultipartFile excel, int sheetNo,
                            @RequestParam(defaultValue = "1") int headLineNum) {
        return ExcelUtil.readExcel(excel, new DemoData2(), sheetNo, headLineNum);
    }

    /**
     * 导出 Excel（一个 sheet）
     */
    @ApiOperation("导出 Excel（一个 sheet）")
    @RequestMapping(value = "writeExcel", method = RequestMethod.GET)
    public void writeExcel(HttpServletResponse response) {
        List<DemoData> list = new ArrayList<>();
        DemoData demoData;
        for (int i = 0; i < 100; i++) {
            demoData = DemoData.builder()
                    .username("download_test1" + i).password("fzPaw" + i)
                    .build();
            list.add(demoData);
        }
        String fileName = "一个 Excel 文件";
        String sheetName = "第一个 sheet";
        ExcelUtil.writeExcel(response, list, fileName, sheetName, new DemoData());
    }

    /**
     * 导出 Excel（多个 sheet）
     */
    @ApiOperation("导出 Excel（多个 sheet）")
    @RequestMapping(value = "writeExcelWithSheets", method = RequestMethod.GET)
    public void writeExcelWithSheets(HttpServletResponse response) {
        List<DemoData> list = new ArrayList<>();
        DemoData demoData;
        for (int i = 0; i < 100; i++) {
            demoData = DemoData.builder()
                    .username("download_test1" + i).password("fzPaw" + i)
                    .build();
            list.add(demoData);
        }
        String fileName = "一个 Excel 文件";
        String sheetName1 = "第一个 sheet";
        String sheetName2 = "第二个 sheet";
        String sheetName3 = "第三个 sheet";

        ExcelUtil.writeExcelWithSheets(response, list, fileName, sheetName1, new DemoData())
                .write(list, sheetName2, new DemoData())
                .write(list, sheetName3, new DemoData())
                .finish();
    }
}
